Popular Searches
Popular Course Categories
Popular Courses

Link Text

Selenium Locators

Link Text in Selenium

Link Text is one of the Selenium WebDriver locator strategies used to identify and interact with hyperlinks on a web page. It locates an anchor element using the complete visible text displayed to the user. Selenium provides the By.linkText() method for locating a hyperlink by its exact visible text.

Link Text is especially useful when a web page contains meaningful and unique hyperlink text such as Login, Register, Contact Us, Download, or View Details.

For structured Selenium learning, you can explore the JustAcademy's Selenium Training Course and use the Register for Course Demo link for a course demonstration.


1. What is Link Text?

Link Text is a Selenium locator used to locate an HTML hyperlink by matching the complete visible text inside an anchor element.

In HTML, hyperlinks are normally created using the <a> tag.

<a href="https://example.com">Login</a>

In this example, Login is the visible link text. Selenium can locate this hyperlink using:

driver.findElement(By.linkText("Login"));

The important point is that By.linkText() searches for the visible text of an anchor element rather than its ID, class, name, or href attribute.


2. Why Link Text is Used in Selenium

Web applications contain many hyperlinks that users click to navigate from one page to another. Selenium automation frequently needs to identify these links and perform actions such as clicking them, reading their text, verifying their presence, or checking their destination.

  • It is easy to understand.
  • It uses the text visible to the user.
  • It is useful for navigation links.
  • It can make automation scripts readable.
  • It is useful when a link has no unique ID.
  • It can be useful for functional and navigation testing.


3. Basic Syntax of Link Text

driver.findElement(By.linkText("Link Text")).click();

The syntax contains three important parts:

  1. driver - Selenium WebDriver instance.
  2. By.linkText() - locator strategy used to find a hyperlink.
  3. "Link Text" - complete visible text of the hyperlink.


4. Basic HTML Example

<html>

<body>

<a href="https://example.com/login">Login</a>

<a href="https://example.com/register">Register</a>

<a href="https://example.com/contact">Contact Us</a>

</body>

</html>

The visible link texts are:

  • Login
  • Register
  • Contact Us

They can be located using:

driver.findElement(By.linkText("Login"));

driver.findElement(By.linkText("Register"));

driver.findElement(By.linkText("Contact Us"));


5. Setting Up Selenium WebDriver

Before using Link Text, Selenium WebDriver must be configured in the Java project.

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

A basic WebDriver setup can be written as:

WebDriver driver = new ChromeDriver();

driver.manage().window().maximize();

driver.get("https://example.com");


6. First Link Text Example

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class LinkTextExample {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.get("https://example.com");

        driver.findElement(By.linkText("More information...")).click();

        driver.quit();

    }

}

The script opens the website, searches for a hyperlink whose complete visible text is More information..., clicks it, and finally closes the browser.


7. Understanding the <a> Tag

Link Text primarily works with hyperlink elements represented by the HTML <a> tag.

<a href="https://example.com">Visit Website</a>

Here:

HTML PartMeaning
<a>Anchor element used to create a hyperlink
hrefDestination URL
Visit WebsiteVisible link text


8. Link Text Uses Exact Visible Text

By.linkText() is designed to match the complete visible text of the hyperlink.

<a href="/login">Login</a>

Correct:

driver.findElement(By.linkText("Login")).click();

An incorrect or incomplete value may not locate the element:

driver.findElement(By.linkText("Log")).click();

For partial visible text, Selenium provides By.partialLinkText().


9. Link Text vs Partial Link Text

FeatureLink TextPartial Link Text
MethodBy.linkText()By.partialLinkText()
MatchingComplete visible textPart of visible text
Example"Login""Log"
PrecisionMore preciseLess precise
Best UseUnique complete link textDynamic or long link text


10. Example of Partial Link Text

<a href="/products">View All Products</a>

Using complete Link Text:

driver.findElement(By.linkText("View All Products")).click();

Using Partial Link Text:

driver.findElement(By.partialLinkText("Products")).click();

Both approaches can locate the link, but they use different matching strategies.


11. Link Text with findElement()

The findElement() method is commonly used when one specific hyperlink needs to be located.

WebElement loginLink = driver.findElement(By.linkText("Login"));

loginLink.click();

The WebElement can also be used for validation:

WebElement loginLink = driver.findElement(By.linkText("Login"));

 

System.out.println(loginLink.getText());

System.out.println(loginLink.isDisplayed());

System.out.println(loginLink.isEnabled());


12. Importing WebElement

import org.openqa.selenium.WebElement;

A complete example:

WebElement link = driver.findElement(By.linkText("Login"));

link.click();


13. findElement() vs findElements() for Links

Selenium provides both findElement() and findElements() for locating web elements.

MethodReturn TypeUse
findElement()WebElementFind one matching element
findElements()List<WebElement>Find multiple matching elements


14. Finding All Links Using Tag Name

When the requirement is to retrieve all hyperlinks on a page, the a tag can be used.

List<WebElement> links = driver.findElements(By.tagName("a"));

Import the List interface:

import java.util.List;

Complete example:

List<WebElement> links = driver.findElements(By.tagName("a"));

System.out.println("Total links: " + links.size());


15. Printing All Link Texts

List<WebElement> links = driver.findElements(By.tagName("a"));

 

for (WebElement link : links) {

    System.out.println(link.getText());

}

This technique is useful when testing navigation menus, footer links, product links, or other collections of hyperlinks.


16. Finding a Specific Link from Multiple Links

List<WebElement> links = driver.findElements(By.tagName("a"));

 

for (WebElement link : links) {

    if (link.getText().equals("Login")) {

        link.click();

        break;

    }

}

This approach can be useful when the page contains multiple links and you want to inspect their visible text programmatically.


17. Link Text with Navigation Menus

Navigation menus commonly contain links such as Home, About, Services, Courses, Contact, and Login.

<nav>

    <a href="/home">Home</a>

    <a href="/about">About Us</a>

    <a href="/services">Services</a>

    <a href="/contact">Contact Us</a>

</nav>

Selenium:

driver.findElement(By.linkText("Home")).click();

driver.findElement(By.linkText("About Us")).click();

driver.findElement(By.linkText("Services")).click();

driver.findElement(By.linkText("Contact Us")).click();


18. Link Text for Login Link

<a href="/login">Login</a>

driver.findElement(By.linkText("Login")).click();


19. Link Text for Registration

<a href="/register">Register</a>

driver.findElement(By.linkText("Register")).click();


20. Link Text for Contact Us

<a href="/contact">Contact Us</a>

driver.findElement(By.linkText("Contact Us")).click();


21. Link Text for Download Links

<a href="/files/report.pdf">Download Report</a>

driver.findElement(By.linkText("Download Report")).click();

Link Text can therefore be useful for testing download links when the visible text is unique.


22. Link Text for Course Links

<a href="/courses/selenium">Selenium Training</a>

driver.findElement(By.linkText("Selenium Training")).click();


23. Link Text for Product Pages

<a href="/products/laptop">Laptop</a>

driver.findElement(By.linkText("Laptop")).click();


24. Link Text for "View Details"

E-commerce websites often contain links such as View Details.

<a href="/product/101">View Details</a>

driver.findElement(By.linkText("View Details")).click();

However, if several products have the same visible text, using only Link Text may not be sufficient to identify the correct product.


25. Duplicate Link Text Problem

Consider the following page:

<a href="/product/1">View Details</a>

<a href="/product/2">View Details</a>

<a href="/product/3">View Details</a>

Using:

driver.findElement(By.linkText("View Details")).click();

may identify the first matching link rather than the specific product intended by the test.

In such cases, a more specific locator such as CSS Selector or XPath should be considered.


26. Link Text with XPath

XPath can provide more control when Link Text is not sufficiently specific.

driver.findElement(By.xpath("//a[text()='View Details']")).click();

A specific link can be located using additional attributes:

driver.findElement(By.xpath("//a[@href='/product/2' and text()='View Details']")).click();


27. Link Text with CSS Selector

CSS selectors can be used when additional attributes are available.

driver.findElement(By.cssSelector("a[href='/product/2']")).click();

CSS Selector is often more appropriate when the visible text is duplicated.


28. Link Text and Case Sensitivity

When using Link Text, the text supplied to Selenium should match the visible text expected by the browser.

driver.findElement(By.linkText("Login")).click();

Do not assume that changing the capitalization will always produce the same result:

driver.findElement(By.linkText("login")).click();

Use the actual visible link text when creating the locator.


29. Link Text with Spaces

Spaces that are part of the visible link text matter.

<a href="/account">My Account</a>

Use:

driver.findElement(By.linkText("My Account")).click();

A locator that does not match the actual visible text may fail to locate the element.


30. Link Text with Long Text

Some applications contain long hyperlinks.

<a href="/article">Read the complete automation testing guide</a>

Complete Link Text:

driver.findElement(By.linkText("Read the complete automation testing guide")).click();

If the complete text is dynamic or difficult to maintain, Partial Link Text or another locator may be more practical.


31. Partial Link Text for Long Links

driver.findElement(By.partialLinkText("automation testing")).click();

Partial Link Text searches for a portion of the visible link text.


32. Link Text with Dynamic Content

Dynamic applications may generate link text that changes depending on data.

<a href="/user/101">Welcome Manish</a>

If the name changes for every test execution, exact Link Text may not be stable.

An alternative can be:

driver.findElement(By.xpath("//a[contains(text(),'Welcome')]")).click();


33. Link Text with Hidden Elements

A hyperlink may exist in the DOM but not be visible on the page.

<a href="/admin" style="display:none">Admin</a>

Finding the element and interacting with it are different operations. Selenium may locate the element, but an attempt to click an invisible element can fail.


34. Checking Whether a Link is Displayed

WebElement link = driver.findElement(By.linkText("Login"));

 

if (link.isDisplayed()) {

    System.out.println("Login link is displayed");

}


35. Checking Whether a Link is Enabled

WebElement link = driver.findElement(By.linkText("Login"));

 

if (link.isEnabled()) {

    System.out.println("Login link is enabled");

}


36. Getting Link Text

WebElement link = driver.findElement(By.linkText("Login"));

 

String text = link.getText();

 

System.out.println("Link text: " + text);


37. Getting href Attribute

Although Link Text identifies an element using visible text, the destination URL can be retrieved using the href attribute.

WebElement link = driver.findElement(By.linkText("Login"));

 

String url = link.getAttribute("href");

 

System.out.println("URL: " + url);


38. Validating Link Text

WebElement link = driver.findElement(By.linkText("Login"));

 

String actualText = link.getText();

 

if (actualText.equals("Login")) {

    System.out.println("Link text is correct");

} else {

    System.out.println("Link text is incorrect");

}


39. Verifying Link Destination

WebElement link = driver.findElement(By.linkText("Login"));

 

String actualUrl = link.getAttribute("href");

 

if (actualUrl.equals("https://example.com/login")) {

    System.out.println("URL is correct");

}


40. Link Text in TestNG

Link Text can be used with TestNG assertions for automated validation.

import org.testng.Assert;

import org.testng.annotations.Test;

 

@Test

public void verifyLoginLink() {

    WebElement link = driver.findElement(By.linkText("Login"));

 

    Assert.assertTrue(link.isDisplayed());

    Assert.assertEquals(link.getText(), "Login");

}


41. Complete TestNG Example

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

public class LinkTextTest {

    WebDriver driver;

 

    @BeforeMethod

    public void setup() {

        driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.get("https://example.com");

    }

 

    @Test

    public void verifyLink() {

        WebElement link = driver.findElement(By.linkText("More information..."));

 

        Assert.assertTrue(link.isDisplayed());

        Assert.assertEquals(link.getText(), "More information...");

    }

 

    @AfterMethod

    public void tearDown() {

        driver.quit();

    }

}


42. Link Text with Explicit Wait

Modern web applications may load links dynamically. In such situations, explicit waits can improve synchronization.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement link = wait.until(

    ExpectedConditions.elementToBeClickable(By.linkText("Login"))

);

 

link.click();

Required imports:

import java.time.Duration;

import org.openqa.selenium.support.ui.WebDriverWait;

import org.openqa.selenium.support.ui.ExpectedConditions;


43. Why Explicit Wait is Useful

  • The link may appear after an AJAX request.
  • The page may load content dynamically.
  • The element may initially be present but not clickable.
  • Network delays may change element availability.
  • Animations may temporarily prevent interaction.


44. Common Exceptions with Link Text

ExceptionPossible Reason
NoSuchElementExceptionLink could not be found
ElementClickInterceptedExceptionAnother element is blocking the link
ElementNotInteractableExceptionLink cannot currently be interacted with
StaleElementReferenceExceptionDOM changed after locating the link
TimeoutExceptionExplicit wait condition was not satisfied


45. NoSuchElementException

This exception can occur when the specified Link Text does not match any available hyperlink.

driver.findElement(By.linkText("Login")).click();

Possible reasons include:

  • Incorrect text.
  • Link not loaded yet.
  • Link is inside an iframe.
  • Page navigation has not completed.
  • Visible text is different from the expected text.


46. ElementClickInterceptedException

This can occur when another element, such as a popup, overlay, cookie banner, or modal, blocks the hyperlink.

A better approach is usually to handle the blocking element rather than immediately using JavaScript.


47. Link Inside an Iframe

If a hyperlink is located inside an iframe, Selenium must switch into the iframe before locating the link.

driver.switchTo().frame("paymentFrame");

 

driver.findElement(By.linkText("Continue")).click();

 

driver.switchTo().defaultContent();


48. Link Inside a Nested Iframe

For nested iframes, Selenium must switch through the frame hierarchy.

driver.switchTo().frame("outerFrame");

driver.switchTo().frame("innerFrame");

 

driver.findElement(By.linkText("Continue")).click();

 

driver.switchTo().defaultContent();


49. Links in Tables

Tables often contain links such as View, Edit, Delete, or Details.

<table>

    <tr>

        <td>John</td>

        <td><a href="/edit/1">Edit</a></td>

    </tr>

</table>

If the Edit link is unique:

driver.findElement(By.linkText("Edit")).click();


50. Links in Product Listings

<div class="product">

    <h2>Laptop</h2>

    <a href="/laptop">View Product</a>

</div>

If multiple products have the same link text, XPath can be used to connect the link with the required product.

driver.findElement(

    By.xpath("//h2[text()='Laptop']/following-sibling::a[text()='View Product']")

).click();


51. Links in Footer

<footer>

    <a href="/privacy">Privacy Policy</a>

    <a href="/terms">Terms & Conditions</a>

</footer>

Selenium:

driver.findElement(By.linkText("Privacy Policy")).click();


52. Link Text in Page Object Model

In the Page Object Model, locators are generally kept inside page classes.

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

 

public class LoginPage {

    WebDriver driver;

    By registerLink = By.linkText("Register");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void clickRegister() {

        driver.findElement(registerLink).click();

    }

}

This approach keeps locators centralized and makes automation code easier to maintain.


53. Reusable Link Utility

public void clickLinkByText(String text) {

    driver.findElement(By.linkText(text)).click();

}

The method can then be reused:

clickLinkByText("Login");

clickLinkByText("Register");

clickLinkByText("Contact Us");


54. Validating Multiple Links

String[] expectedLinks = {

    "Home",

    "About Us",

    "Services",

    "Contact Us"

};

 

for (String linkText : expectedLinks) {

    WebElement link = driver.findElement(By.linkText(linkText));

    System.out.println(linkText + " is displayed: " + link.isDisplayed());

}


55. Link Text in a Navigation Test

driver.findElement(By.linkText("Products")).click();

 

Assert.assertTrue(driver.getTitle().contains("Products"));

This verifies both the interaction and the resulting navigation.


56. Link Text and Browser Navigation

Link Text can be used to test navigation flows such as:

Home

  ↓

Products

  ↓

Product Details

  ↓

Cart

  ↓

Checkout

Each navigation step can be automated and validated using appropriate link locators.


57. Link Text for Authentication Flow

driver.findElement(By.linkText("Login")).click();

 

driver.findElement(By.id("username")).sendKeys("user");

driver.findElement(By.id("password")).sendKeys("password");

driver.findElement(By.id("loginBtn")).click();

Link Text can therefore be part of larger end-to-end automation flows.


58. Link Text for Registration Flow

driver.findElement(By.linkText("Register")).click();

 

driver.findElement(By.id("name")).sendKeys("Test User");

driver.findElement(By.id("email")).sendKeys("[email protected]");


59. Link Text for Course Navigation

Educational websites frequently use links such as:

  • Courses
  • Selenium Training
  • Download Syllabus
  • Register
  • Contact Us
  • Book Free Demo

These links can be automated using Link Text when the visible text is unique and stable.


60. Link Text vs ID Locator

FeatureLink TextID
TargetVisible link textid attribute
Typical Element<a>Any HTML element
MethodBy.linkText()By.id()
ReadabilityHighHigh
UniquenessDepends on visible textUsually high when ID is unique


61. Link Text vs Name Locator

FeatureLink TextName
UsesVisible hyperlink textname attribute
MethodBy.linkText()By.name()
Common TargetAnchorForm elements


62. Link Text vs Class Name

FeatureLink TextClass Name
Based OnVisible textclass attribute
MethodBy.linkText()By.className()
Typical UseUnique hyperlinkElement with a known class


63. Link Text vs CSS Selector

CSS selectors can use multiple attributes and structural relationships, while Link Text focuses on visible text.

driver.findElement(By.linkText("Login")).click();

CSS alternative:

driver.findElement(By.cssSelector("a[href='/login']")).click();


64. Link Text vs XPath

XPath is generally more flexible when a link must be identified based on text plus other attributes or its position in the DOM.

driver.findElement(By.xpath("//a[text()='Login']")).click();

Link Text is simpler when the complete visible text uniquely identifies the hyperlink.


65. When to Prefer Link Text

  • The target is an anchor element.
  • The complete visible text is known.
  • The text is unique on the page.
  • The text is stable between releases.
  • The locator should be easy for testers to understand.


66. When Not to Prefer Link Text

  • The link text is duplicated.
  • The link text changes frequently.
  • The text is generated dynamically.
  • The link contains only an icon.
  • The element is not an anchor element.
  • A stable unique ID is available.
  • A more specific CSS or XPath locator is required.


67. Common Mistake: Using Incomplete Text

<a href="/courses">Selenium Training Course</a>

Incorrect:

driver.findElement(By.linkText("Selenium")).click();

Correct:

driver.findElement(By.linkText("Selenium Training Course")).click();

If only a portion is required, consider:

driver.findElement(By.partialLinkText("Selenium")).click();


68. Common Mistake: Ignoring Duplicate Links

If a page contains multiple links with the same text, relying only on Link Text may lead to the wrong element being selected.

Use a more specific locator when the link needs to be associated with a particular row, card, product, or section.


69. Common Mistake: Using Link Text for Buttons

Link Text is intended for hyperlinks. A button such as:

<button>Login</button>

is not the same as:

<a href="/login">Login</a>

For a button, use an appropriate locator such as ID, CSS, XPath, or another suitable strategy.


70. Common Mistake: Ignoring Dynamic Text

Suppose the application displays:

<a href="/user">Welcome John</a>

and later:

<a href="/user">Welcome Sarah</a>

Hardcoding the complete Link Text can make the test unstable. In such situations, a more stable attribute or a carefully designed XPath may be better.


71. Common Mistake: Not Handling Popups

If a popup or cookie banner covers the hyperlink, clicking it may fail. The automation should first handle the popup when appropriate.


72. Best Practices for Link Text

  • Use complete visible text when it is unique and stable.
  • Prefer stable locators over dynamic text.
  • Avoid Link Text when many links have the same text.
  • Use explicit waits for dynamically loaded links.
  • Keep locators in Page Object classes.
  • Validate both link visibility and navigation when appropriate.
  • Use CSS or XPath when additional precision is required.
  • Avoid unnecessary JavaScript clicks.
  • Use meaningful and maintainable locator strategies.


73. Practical Example: Website Navigation

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class NavigationTest {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.get("https://example.com");

        driver.findElement(By.linkText("More information...")).click();

        System.out.println(driver.getTitle());

        driver.quit();

    }

}


74. Practical Example: Checking All Links

List<WebElement> links = driver.findElements(By.tagName("a"));

 

for (WebElement link : links) {

    String text = link.getText();

    String href = link.getAttribute("href");

    System.out.println("Text: " + text);

    System.out.println("URL: " + href);

}


75. Practical Example: Click Link Only If Displayed

WebElement link = driver.findElement(By.linkText("Login"));

 

if (link.isDisplayed() && link.isEnabled()) {

    link.click();

}


76. Practical Example: Verify Link Destination

WebElement link = driver.findElement(By.linkText("Login"));

 

String expectedUrl = "https://example.com/login";

String actualUrl = link.getAttribute("href");

 

if (expectedUrl.equals(actualUrl)) {

    System.out.println("Destination URL is correct");

} else {

    System.out.println("Destination URL is incorrect");

}


77. Practical Example: Search Link by Text

List<WebElement> links = driver.findElements(By.tagName("a"));

 

for (WebElement link : links) {

    if (link.getText().equals("Login")) {

        link.click();

        break;

    }

}


78. Real-World Link Testing Scenarios

ScenarioExample LinkTesting Action
LoginLoginClick and verify login page
RegistrationRegisterOpen registration form
NavigationProductsVerify products page
DownloadDownload ReportVerify download behavior
SupportContact UsOpen contact page
CourseSelenium TrainingOpen course details


79. Link Testing Checklist

  • Verify the link is present.
  • Verify the link is visible.
  • Verify the link text.
  • Verify the link is clickable.
  • Verify the destination URL.
  • Verify navigation after clicking.
  • Handle dynamic loading.
  • Handle duplicate link text.
  • Handle iframe content where required.
  • Validate broken links separately when required.


80. Link Text Locator Syntax Summary

PurposeSyntax
Locate by complete textBy.linkText("Login")
Locate by partial textBy.partialLinkText("Log")
Click linkdriver.findElement(By.linkText("Login")).click()
Store linkWebElement link = driver.findElement(By.linkText("Login"));
Get textlink.getText()
Get destinationlink.getAttribute("href")


81. Interview Question: What is Link Text in Selenium?

Link Text is a Selenium locator strategy used to locate a hyperlink based on its complete visible text. Selenium provides the By.linkText() method for this purpose.


82. Interview Question: What is the Syntax of Link Text?

driver.findElement(By.linkText("Login")).click();


83. Interview Question: What is Partial Link Text?

Partial Link Text locates an anchor element using a portion of its visible text.

driver.findElement(By.partialLinkText("Login")).click();


84. Interview Question: Difference Between Link Text and Partial Link Text?

Link TextPartial Link Text
Matches complete visible textMatches a portion of visible text
More preciseMore flexible
By.linkText()By.partialLinkText()


85. Interview Question: Can Link Text Locate a Button?

No. Link Text is intended for hyperlink elements. A button should generally be located using an appropriate attribute-based, CSS, XPath, or other supported locator strategy.


86. Interview Question: What Happens if Multiple Links Have the Same Text?

If multiple elements match the same locator, findElement() returns the first matching element in the current search context. To identify a particular link, use a more specific locator or narrow the search context.


87. Interview Question: How Can You Handle Dynamic Link Text?

Use a stable attribute when available. Otherwise, carefully designed XPath or Partial Link Text may be used when it produces a unique and stable match.


88. Interview Question: How Do You Verify Link Text?

WebElement link = driver.findElement(By.linkText("Login"));

 

Assert.assertEquals(link.getText(), "Login");


89. Interview Question: How Do You Get the URL of a Link?

WebElement link = driver.findElement(By.linkText("Login"));

 

String url = link.getAttribute("href");


90. Interview Question: How Do You Find All Links?

List<WebElement> links = driver.findElements(By.tagName("a"));


91. Interview Question: Can Link Text Be Used with Page Object Model?

Yes. Link Text locators can be declared as fields inside Page Object classes.

By loginLink = By.linkText("Login");


92. Interview Question: Why Can Link Text Become Unstable?

Link Text can become unstable when the visible text is changed frequently, localized into different languages, generated dynamically, or duplicated across the page.


93. Link Text in Internationalized Applications

Applications supporting multiple languages may display different link text depending on the selected language.

English: Login

French: Connexion

Spanish: Iniciar sesión

A test that depends on exact English text may fail when the application language changes. In such cases, language-independent attributes or other stable locators may be preferable.


94. Link Text and Accessibility

Meaningful link text also helps users understand where a hyperlink leads. Automation testers should prefer clear, stable link text when designing or validating test scenarios.


95. Link Text and Maintainability

A locator is maintainable when it remains valid despite unrelated UI changes. If a link's visible text changes frequently, relying exclusively on Link Text can increase maintenance effort.


96. Link Text and Dynamic Web Applications

Modern web applications frequently update content without a complete page refresh. A link may be created after JavaScript execution or an API response. Explicit waits and stable locator strategies should be used when necessary.


97. Recommended Locator Decision Flow

Need to locate a hyperlink

        ↓

Is the complete visible text unique and stable?

        ↓

      Yes

        ↓

Use By.linkText()

        ↓

       No

        ↓

Is partial text stable and unique?

        ↓

      Yes

        ↓

Use By.partialLinkText()

        ↓

       No

        ↓

Use a stable ID, CSS Selector, or XPath


98. Link Text Best-Practice Example

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement loginLink = wait.until(

    ExpectedConditions.elementToBeClickable(By.linkText("Login"))

);

 

Assert.assertEquals(loginLink.getText(), "Login");

 

loginLink.click();

This example combines a readable locator, explicit wait, text validation, and interaction.


99. Link Text Automation Project Example

Consider an e-commerce application containing the following navigation:

Home

Products

Categories

Offers

Login

Register

Contact Us

A Selenium test can verify that the important navigation links are available.

String[] navigationLinks = {

    "Home",

    "Products",

    "Categories",

    "Offers",

    "Login",

    "Register",

    "Contact Us"

};

 

for (String text : navigationLinks) {

    WebElement link = driver.findElement(By.linkText(text));

    System.out.println(text + ": " + link.isDisplayed());

}


100. Advanced Project: Link Validation Framework

A reusable link validation framework can perform the following operations:

  1. Collect all hyperlinks.
  2. Read visible link text.
  3. Read href attributes.
  4. Verify visibility.
  5. Click selected links.
  6. Validate navigation.
  7. Generate test reports.
  8. Record failures for debugging.


101. Link Text Automation Workflow

Open Browser

      ↓

Navigate to Application

      ↓

Identify Required Hyperlink

      ↓

Use By.linkText()

      ↓

Wait for Element

      ↓

Verify Visibility

      ↓

Verify Link Text

      ↓

Click Link

      ↓

Validate Destination

      ↓

Generate Test Result

      ↓

Close Browser


102. Link Text vs Other Selenium Locators

LocatorMethodTypical Usage
IDBy.id()Unique element ID
NameBy.name()name attribute
Class NameBy.className()class attribute
Tag NameBy.tagName()HTML tag
Link TextBy.linkText()Complete hyperlink text
Partial Link TextBy.partialLinkText()Partial hyperlink text
CSS SelectorBy.cssSelector()CSS-based selection
XPathBy.xpath()Advanced element selection


103. Important Points to Remember

  • Link Text is mainly used for hyperlinks.
  • The Selenium method is By.linkText().
  • It works with the complete visible text of a link.
  • For partial text, use By.partialLinkText().
  • Duplicate link text can cause incorrect element selection.
  • Dynamic link text can make tests unstable.
  • Explicit waits are useful for dynamically loaded links.
  • XPath and CSS selectors provide additional flexibility.
  • Page Object Model can centralize Link Text locators.
  • Always prefer stable and maintainable locators.


104. Quick Revision

QuestionAnswer
What is Link Text?A locator strategy for finding hyperlinks by complete visible text.
Method?By.linkText()
Partial text method?By.partialLinkText()
Typical HTML element?<a>
Can it locate buttons?No, it is intended for links.
What if links have duplicate text?Use a more specific locator.
How to get href?getAttribute("href")
How to get visible text?getText()


105. Final Conclusion

Link Text is a simple and readable Selenium locator strategy for identifying hyperlinks through their complete visible text. It is particularly useful for navigation links, login links, registration links, course links, download links, and other hyperlinks whose text is unique and stable.

The basic syntax is:

driver.findElement(By.linkText("Login")).click();

When the complete text is not suitable, By.partialLinkText(), CSS Selector, XPath, ID, or another stable locator can be used depending on the structure of the application.

For professional Selenium automation, Link Text should be combined with proper waits, validation, Page Object Model practices, reusable utilities, and stable locator strategies.

For further Selenium learning and practical automation training, visit the JustAcademy's Selenium Training Course or use the Register for Course Demo link.

whatsapp